//import THREE from "../../../node_modules/three/build/three.module.js"
import * as THREE from 'three'
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls.js'
let camera, scene, renderer, controls;

export default {
  data() {
    return {
      mouse: new THREE.Vector2(),
      raycaster: new THREE.Raycaster(),
      rollOverMesh: null,
      isShiftDown: false,
      plane:null,
      cubeGeo:null,
      cubeMaterial:null,
      objects: []
    }
  },
  watch: {},
  mounted() {
    this.init();
    this.render();
  },
  methods: {
    init() {
      //设置相机 
      camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 10000);
      camera.position.set(500, 800, 1300);
      camera.lookAt(0, 0, 0);
      //设置场景
      scene = new THREE.Scene();
      scene.background = new THREE.Color(0xf0f0f0);

      // 设置辅助方块
      const rollOverGeo = new THREE.BoxGeometry(50, 50, 50);
      let rollOverMaterial = new THREE.MeshBasicMaterial({
        color: 0xff0000,
        opacity: 0.5,
        transparent: true
      });
      this.rollOverMesh = new THREE.Mesh(rollOverGeo, rollOverMaterial);
      scene.add(this.rollOverMesh);

      // 方块
      var texture = require('../../assets/textures/square-outline-textured.png')
      // var texture = require('../../assets/textures/crate.gif')
      this.cubeGeo = new THREE.BoxGeometry(50, 50, 50);
      this.cubeMaterial = new THREE.MeshLambertMaterial({
        color: 0xfeb74c,
        map: new THREE.TextureLoader().load(texture)
      });
      // grid
      const gridHelper = new THREE.GridHelper(2000, 40);
      scene.add(gridHelper);

      //
      // this.raycaster = new THREE.Raycaster();
      // this.mouse1 = new THREE.Vector2();
      //console.log(this.mouse1)

      const geometry = new THREE.PlaneGeometry(2000, 2000);
      geometry.rotateX(-Math.PI / 2);

      this.plane = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({
        visible: true
      }));
      scene.add(this.plane);

      this.objects.push(this.plane);

      // lights
      const ambientLight = new THREE.AmbientLight(0x606060);
      scene.add(ambientLight);

      const directionalLight = new THREE.DirectionalLight(0xffffff);
      directionalLight.position.set(1, 0.75, 0.5).normalize();
      scene.add(directionalLight);

      let container = document.getElementById('container');

      renderer = new THREE.WebGLRenderer({
        antialias: true
      });
      renderer.setPixelRatio(window.devicePixelRatio);
      renderer.setSize(container.clientWidth, container.clientHeight);
      container.appendChild(renderer.domElement);

      controls = new OrbitControls( camera, renderer.domElement );
			// controls.target.set( 0, 0.5, 0 );
			controls.update();
			controls.enablePan = false;
			controls.enableDamping = true;

      this.animate()

      document.addEventListener('mousemove', this.onDocumentMouseMove);
      //document.addEventListener( 'mousedown', this.onDocumentMouseDown );
      document.addEventListener( 'keydown', this.onDocumentKeyDown );
      document.addEventListener( 'keyup', this.onDocumentKeyUp );
      //右键
      document.addEventListener( 'contextmenu', this.onDocumentMouseDown );
      //

      window.addEventListener('resize', this.onWindowResize);
      
    },
    render() {
      renderer.render(scene, camera);
    },
    /***********************************鼠标事件***********************************/
    onDocumentMouseMove(event1) {

      event1.preventDefault();

      this.mouse.set((event1.clientX / window.innerWidth) * 2 - 1, -(event1.clientY / window.innerHeight) * 2 + 1);

      this.raycaster.setFromCamera(this.mouse, camera);

      const intersects = this.raycaster.intersectObjects(this.objects);

      if (intersects.length > 0) {

        const intersect = intersects[0];
        
        this.rollOverMesh.position.copy(intersect.point).add(intersect.face.normal);
        this.rollOverMesh.position.divideScalar(50).floor().multiplyScalar(50).addScalar(25);

      }

      this.render();

    },
    onWindowResize() {
      // container.clientWidth, container.clientHeight
      let container = document.getElementById('container');

      camera.aspect = container.clientWidth / container.clientHeight;
      camera.updateProjectionMatrix();

      renderer.setSize(container.clientWidth, container.clientHeight);

    },
    onDocumentMouseDown(event) {
      
      event.preventDefault();

      this.mouse.set((event.clientX / window.innerWidth) * 2 - 1, -(event.clientY / window.innerHeight) * 2 + 1);

      this.raycaster.setFromCamera(this.mouse, camera);

      const intersects = this.raycaster.intersectObjects(this.objects);

      if (intersects.length > 0) {

        const intersect = intersects[0];

        // delete cube

        if (this.isShiftDown) {

          if (intersect.object !== this.plane) {

            scene.remove(intersect.object);

            this.objects.splice(this.objects.indexOf(intersect.object), 1);

          }

          // create cube

        } else {

          const voxel = new THREE.Mesh(this.cubeGeo, this.cubeMaterial);
          voxel.position.copy(intersect.point).add(intersect.face.normal);
          voxel.position.divideScalar(50).floor().multiplyScalar(50).addScalar(25);
          scene.add(voxel);

          this.objects.push(voxel);

        }

        this.render();

      }

    },
    onDocumentKeyDown( event ) {

      switch ( event.keyCode ) {

        case 16: this.isShiftDown = true; break;

      }

    },

    onDocumentKeyUp( event ) {

      switch ( event.keyCode ) {

        case 16: this.isShiftDown = false; break;

      }

    },
    animate() {

      requestAnimationFrame( this.animate );
      controls.update();

      renderer.render( scene, camera );

    }


  }
}
